package com.zsd.android.dblib.db;

import android.database.sqlite.SQLiteDatabase;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class BaseDaoFactory {

    private static volatile BaseDaoFactory instance;
    private SQLiteDatabase sqLiteDatabase;
    private String sqLitePath;

    //设计要给数据库连接池，new 容器，只要new个一次，下次就不会再创建了。考虑多线程问题
    protected Map<String, BaseDao> map = Collections.synchronizedMap(new HashMap<String, BaseDao>());

    protected BaseDaoFactory() {
        sqLitePath = "data/data/com.zsd.android.dblib/ne.db";
        sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqLitePath, null);
    }

    public static BaseDaoFactory getInstance() {
        BaseDaoFactory factory = instance;
        if (factory == null) {
            synchronized (BaseDaoFactory.class) {
                if (factory == null) {
                    factory = new BaseDaoFactory();
                    instance = factory;
                }
            }
        }
        return factory;
    }

    /**
     * 产生BaseDao对象
     *
     * @param entityClass 操作数据对应的Java类型
     * @param <T>
     * @return
     */
    public <T> BaseDao<T> getBaseDao(Class<T> entityClass) {
        BaseDao baseDao = null;
        try {
            baseDao = BaseDao.class.newInstance();
            baseDao.init(sqLiteDatabase, entityClass);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return baseDao;
    }

    public <T extends BaseDao, M> T getBaseDao(Class<T> daoClass, Class<M> entityClass) {
        String key = daoClass.getSimpleName();
        BaseDao baseDao = map.get(key);
        if (baseDao != null) {
            return (T) baseDao;
        }
        try {
            baseDao = daoClass.newInstance();
            baseDao.init(sqLiteDatabase, entityClass);
            map.put(key, baseDao);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) baseDao;
    }
}
